


package com.comtom.soft.thrift.server;

import org.apache.thrift.TMultiplexedProcessor;
import org.apache.thrift.TProcessor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Service;

import com.comtom.soft.thrift.common.IpNetworkResolve;
import com.comtom.soft.thrift.common.RegisterUtil;
import com.comtom.soft.thrift.service.IpResolve;
import com.comtom.soft.thrift.service.ThriftServerRegister;

/**
 * @author nobody
 * 自动注册服务检测
 */
@Service
public class AutoRegisterService implements BeanPostProcessor{

	@Autowired
	private TMultiplexedProcessor processor;
	
	@Autowired
	private ThriftServerRegister thriftServerRegister;
	
	private IpResolve ipResolve;
	
	private String version="";
	
	private Integer port = 8299;
	
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName)
			throws BeansException {
		Class<?> clazz=RegisterUtil.getIfaceClass(bean);
		if(clazz==null){
			return bean;
		}
		TProcessor tprocessor = RegisterUtil.constructorProssor(clazz, bean);
		if(tprocessor==null){
			return bean;
		}
		String serviceName=clazz.getEnclosingClass().getSimpleName();
		processor.registerProcessor(serviceName, tprocessor);
		if(ipResolve==null){
			ipResolve=new IpNetworkResolve();
		}
		String serviceClass=clazz.getEnclosingClass().getName();
		String addressBuild=ipResolve.getServerIp()+":"+port+":"+serviceName;
		thriftServerRegister.register(serviceClass, version, addressBuild);
		return bean;
	}

	/**
	 * @param processor the processor to set
	 */
	public void setProcessor(TMultiplexedProcessor processor) {
		this.processor = processor;
	}

	/**
	 * @param thriftServerRegister the thriftServerRegister to set
	 */
	public void setThriftServerRegister(ThriftServerRegister thriftServerRegister) {
		this.thriftServerRegister = thriftServerRegister;
	}

	/**
	 * @param version the version to set
	 */
	public void setVersion(String version) {
		this.version = version;
	}

	/**
	 * @param port the port to set
	 */
	public void setPort(Integer port) {
		this.port = port;
	}
	
}
